import { login, logout, getInfo, getRoleMenu, getMenu } from '@/api/user'
import { miniAppList } from '@/api/common'
import { getToken, setToken, removeToken, setUser, resetUser, getUser } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import warterMark from '@/utils/warterMark'
const state = {
  token: getToken(),
  name: '',
  avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
  introduction: '',
  roles: [],
  menu: [],
  currentMenuId: import.meta.env.MODE === 'production' ? '1953' : '2187', // 2187 是测试环境默认在掌权配置的id 1953是正式的环境默认的id
  currentRouter: {},
  button: [],
  userMsg: {
    username: '',
    distributor_name: ''
  },
  userInfo: {},
  axiosCancelList: [],
  miniAppList: [], // 小程序列表list,
  // 储存当前选择的小程序ID
  mini_app_id: window.localStorage.getItem('mini_app_id') || null,
  // 储存当前选择的小程序
  routerItem: window.localStorage.getItem('routerItem') ? JSON.parse(window.localStorage.getItem('routerItem')) : { name: '全部' },
  buttonInfo: {}
}
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_USERMSG: (state, userMsg) => {
    state.userMsg = userMsg
  },
  SET_MENU: (state, menu) => {
    state.menu = menu
  },
  SET_CURRENT_MENU_ID: (state, menuId) => {
    state.currentMenuId = menuId
  },
  SET_CURRENT_ROUTER: (state, router) => {
    state.currentRouter = router
  },
  SET_USERINFO: (state, info) => {
    state.userInfo = info
    const name = info.username || '罗盘'
    const phone = info.phone.toString() || ''
    console.log(`warterMark:${name}-${phone.substr(-4)}`)
    warterMark.set(`${name}-${phone.substr(-4)}`)
  },
  SET_BUTTONINFO: (state, buttonInfo) => {
    state.buttonInfo = buttonInfo
  },
  set_miniAppList(state, data) {
    state.miniAppList = data
  },
  set_mini_app_id(state, data) {
    state.mini_app_id = data
  },
  set_axiosCancelList: (state, data) => {
    state.axiosCancelList = data
  },
  // 导航选择的当前小程序
  set_routerItem(state, data) {
    state.routerItem = data
    window.localStorage.setItem('routerItem', JSON.stringify(data))
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then((response) => {
          const { data } = response
          commit('SET_TOKEN', data.data.token)
          // commit('SET_USERMSG', { username: data.data.username })
          setUser({ username: data.data.username, distributor_name: data.data.distributor_name })
          setToken(data.data.token)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  ssoLogin({ commit }, data) {
    commit('SET_TOKEN', data.token)
    setToken(data.token)
    setUser({ username: data.username, distributor_name: data.distributor_name })
  },
  // 掌权登录
  ZqLogin({ commit }, token) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', token)
      setToken(token)
      resolve()
    })
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then((response) => {
          const { data } = response
          if (!data) {
            return reject('Verification failed, please Login again.')
          }
          const user_data = data
          commit('SET_USERINFO', user_data)
          commit('SET_BUTTONINFO', user_data.operation_auth)
          commit('SET_NAME', user_data.username)
          commit('SET_AVATAR', user_data.headface)
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // get
  async getMenuRouter({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      getMenu()
        .then((response) => {
          let list = []
          const { data } = response
          // || window.location.host.indexOf('zwwlkj03.top') !== -1
          const allMiniItem = window.location.host.indexOf('wozhangwan.com') !== -1 ? '1953' : '2187'
          const allMiniApp = data.find(item => item.id === allMiniItem) // 全部的时候的路由
          const miniItem = window.location.host.indexOf('wozhangwan.com') !== -1 ? '1954' : '2188'
          const miniItemApp = data.find(item => item.id === miniItem) // 小程序的路由
          console.log(allMiniApp, miniItemApp, allMiniItem, miniItem, '路由ID')
          miniAppList({ belong_auth: 1 }).then(res => {
            if (res.data.length > 0) {
              if (miniItemApp && miniItemApp.child) { // 小程序路由权限
                res.data.map(item => {
                  item.child = miniItemApp.child
                  item.router = miniItemApp.router
                  item.mini_app_id = item.id
                })
                list = [miniItemApp, ...res.data]
              } else { // 小程序路由权限不存在
                allMiniApp ? list = [allMiniApp] : list = []
              }
              allMiniApp ? list = [allMiniApp, ...res.data] : (list = res.data, commit('SET_CURRENT_MENU_ID', res.data[0].id || ''))
              console.log(list)
              commit('SET_MENU', list)
              console.log(list)
              resolve(list)
            } else {
              let list = []
              allMiniApp ? list = [allMiniApp] : list = []
              commit('SET_MENU', list)
              resolve(list)
            }
          }, error => {
            commit('SET_MENU', data)
            resolve(data)
          })
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  requestMiniApp({ commit, state }, data) {
    miniAppList(data).then(res => {
      if (res.status_code === 1) {
        commit('set_miniAppList', res.data)
      }
    })
  },
  selectMenu({ commit }, menuId) {
    return new Promise((resolve, reject) => {
      commit('SET_CURRENT_MENU_ID', menuId)
      resolve()
    })
  },
  selectMenuRouter({ commit }, router) {
    // 设置 当前  激活 高亮的路由 直接设置 SET_CURRENT_ROUTER 等于 当前的路由对象
    return new Promise((resolve, reject) => {
      commit('SET_CURRENT_ROUTER', router)
      resolve()
    })
  },
  getMenu({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      getRoleMenu().then((response) => {
        commit('SET_MENU', response.data.data)
        resolve(response.data.data)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_MENU', null)
          removeToken()
          resetRouter()

          // reset visited views and cached views
          // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
          dispatch('tagsView/delAllViews', null, { root: true })

          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_MENU', null)
      removeToken()
      resetUser()
      resolve()
    })
  },
  setUser({ commit }) {
    return new Promise((resolve) => {
      const user = getUser()
      if (user) {
        const userMsg = JSON.parse(user)
        commit('SET_USERMSG', { username: userMsg.username, distributor_name: userMsg.distributor_name })
        resolve(userMsg)
      } else {
        resolve(false)
      }
    })
  },
  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
